package com.ebeitech.auction.view.auction;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ebeitech.auction.R;
import com.ebeitech.auction.bean.Auction;
import com.ebeitech.auction.bean.AuctionBidder;
import com.ebeitech.auction.bean.AuctionPhase;
import com.ebeitech.auction.bean.AuctionUser;
import com.ebeitech.auction.constants.CommonConstants;
import com.ebeitech.auction.domain.ChatMessage;
import com.ebeitech.auction.domain.dao.ChatMessageDao;
import com.ebeitech.auction.http.EbeiErrorCode;
import com.ebeitech.auction.http.HttpService;
import com.ebeitech.auction.http.service.HttpAuctionServiceRx;
import com.ebeitech.auction.view.homepage.AuctionAdapter;
import com.ebeitech.auction.view.homepage.BaseActivity;
import com.ebeitech.auction.view.homepage.HomepageActivity;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/11/1.
 */
public class AuctionLiveFragment extends Fragment {

	@BindView(R.id.view_not_begin)
	View viewNotBegin;
	@BindView(R.id.view_auction_info)
	View viewAuctionInfo;
	@BindView(R.id.scrollview_phase)
	HorizontalScrollView scrollviewPhase;
	@BindView(R.id.view_phase)
	LinearLayout viewPhase;
	@BindView(R.id.view_bottom)
	View viewBottom;
	@BindView(R.id.iv_menu)
	ImageView ivMenu;
	@BindView(R.id.view_operate)
	LinearLayout viewOperate;
	@BindView(R.id.view_input)
	LinearLayout viewInput;
	@BindView(R.id.et_message)
	EditText etMessage;
	@BindView(R.id.btn_send)
	Button btnSend;
	@BindView(R.id.btn_operate1)
	Button btnOperate1;
	@BindView(R.id.btn_operate2)
	Button btnOperate2;
	@BindView(R.id.listView)
	ListView mListView;
	@BindView(R.id.view_begin)
	View mBeginView;
	@BindView(R.id.tv_phaseName)
	TextView mTvPhaseName;
	@BindView(R.id.tv_company)
	TextView mTvCompany;
	@BindView(R.id.tv_currentPrice)
	TextView mTvCurrentPrice;
	Unbinder unbinder;

	private Context mContext;
	private BaseAdapter mAdapter;
	private List<ChatMessage> mMessages = new ArrayList<ChatMessage>();
	private String mLoadMessageJson;

	private String mUserId;

	private Auction mAuction;
	private int mCurrentTab;

	private OnChangeListener mOnChangeListener;

	private HttpService mHttpService;
	private AuctionPhase mAuctionPhase;
	private AuctionUser mAuctionUser;
	private ChatMessageDao mChatMessageDao;
	private CommonAlertDialogFragment mProgressDialog;

	ViewTreeObserver vtObserver;
	int scrollDiff;

	ViewTreeObserver.OnGlobalLayoutListener listener;

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				String action = intent.getAction();
				if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(action)) {
					ChatMessage chatMessage = (ChatMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
					if (chatMessage != null) {
						// 先看是否是本房间的信息
						if (!StringUtil.getDefaultString(mAuction.getAuctionId()).equals(chatMessage.getAuctionId())) {
							return;
						}

						boolean isNeedAdd = true;
						if (ChatMessage.MESSAGE_TYPE_NORMAL.equals(chatMessage.getMessageType())
								|| ChatMessage.MESSAGE_TYPE_COMMAND_SEND.equals(chatMessage.getMessageType())) {
							// 把当前的消息状态改为发送成功
							for (int i = mMessages.size() - 1; i > -1; i--) {
								ChatMessage chatMessageT = mMessages.get(i);
								if (StringUtil.getDefaultString(chatMessage.getMessageId()).equals(chatMessageT.getMessageId())) {
									mMessages.set(i, chatMessage);
									isNeedAdd = false;
									break;
								}
							}
						}
						if (isNeedAdd && !mMessages.contains(chatMessage)) {
							mMessages.add(chatMessage);
						}
						mAdapter.notifyDataSetChanged();
						mListView.setSelection(mMessages.size() - 1);

						if (ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL.equals(chatMessage.getMessageType())) {
							// 如果消息是撤回,就不管最高价,直接用撤回消息里返回的价格
							mAuctionPhase.setPhaseResult(chatMessage.getPrice());
							mAuctionPhase.setPhaseResultRate(chatMessage.getPhaseResultRate());
							mAuctionPhase.setPhaseOurResult(chatMessage.getPhaseOurResult());
							mAuctionPhase.setPhaseOurResultRate(chatMessage.getPhaseOurResultRate());
							AuctionBidder resultBidder = new AuctionBidder();
							resultBidder.setBidderAuctionCode(chatMessage.getAuctionBidderCode());
							resultBidder.setBidderName(chatMessage.getBidderName());
							mAuctionPhase.setResultBidder(resultBidder);
							updateTopView(false);
						} else if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
								|| ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(chatMessage.getMessageType())) {
							// 如果是递增,新的报价必须大于当前报价;递减的话必须小于
							boolean isValid = false;
							float oldResult = 0, newResult = 0;
							try {
								oldResult = Float.valueOf(mAuctionPhase.getPhaseResult());
								newResult = Float.valueOf(chatMessage.getPrice());
							} catch (Exception e) {}
							if (AuctionPhase.QUOTES_TYPE_ADD.equals(mAuctionPhase.getQuotesTypeCode()) && newResult > oldResult) {
								isValid = true;
							} else if (AuctionPhase.QUOTES_TYPE_MINUS.equals(mAuctionPhase.getQuotesTypeCode()) && newResult < oldResult) {
								isValid = true;
							}
							if (!isValid) {
								return;
							}

							// 如果消息是出价的消息,要更新现有的报价
							mAuctionPhase.setPhaseResult(chatMessage.getPrice());
							mAuctionPhase.setPhaseResultRate(chatMessage.getPhaseResultRate());
							AuctionBidder resultBidder = new AuctionBidder();
							resultBidder.setBidderAuctionCode(chatMessage.getAuctionBidderCode());
							resultBidder.setBidderName(chatMessage.getBidderName());
							mAuctionPhase.setResultBidder(resultBidder);
							if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())) {
								mAuctionPhase.setPhaseOurResult(chatMessage.getPrice());
								mAuctionPhase.setPhaseOurResultRate(chatMessage.getPhaseResultRate());
							}
							updateTopView(false);
						} else if (ChatMessage.MESSAGE_TYPE_PHASE_SWITCH.equals(chatMessage.getMessageType())) {
							// 如果消息是阶段切换的消息,要更新阶段
							mAuctionPhase.setPhaseState("0");
							List<AuctionPhase> auctionPhases = mAuction.getAuctionPhases();
							boolean isFirstBegin = false, isEnd = false;
							for (int i = 0; i < auctionPhases.size(); i++) {
								AuctionPhase auctionPhase = auctionPhases.get(i);
								if (StringUtil.getDefaultString(chatMessage.getNextPhaseId()).equals(auctionPhase.getPhaseId())) {
									// 看看是不是大于当前阶段
									if (i > 0 && !(mAuctionPhase.getPhaseSort() < auctionPhase.getPhaseSort())) {
										mAuctionPhase.setPhaseState("1");
										return;
									}

									auctionPhase.setPhaseState("1");
									auctionPhase.setPhaseResult(auctionPhase.getStartPrice());
									auctionPhase.setPhaseOurResult(auctionPhase.getStartPrice());
									// 如果是第一个阶段开始,就把拍卖状态改为进行中
									if (i == 0) {
										isFirstBegin = true;
									}
								}
								if (StringUtil.isEmpty(chatMessage.getNextPhaseId())) {
									// 如果是最后一个阶段结束,就把拍卖状态改为结束
									if (i == auctionPhases.size() - 1) {
										isEnd = true;
									}
								}
							}
							if (isFirstBegin) {
								mAuction.setStateCode(CommonConstants.STATE_BEGINNING);
								updateView();
							} else if (isEnd) {
								mAuction.setStateCode(CommonConstants.STATE_FINISHED);
								updateView();
							} else {
								updateTopView(false);
							}
							// 阶段有变化就要刷新页面
							mAdapter.notifyDataSetChanged();
							mListView.post(new Runnable() {
								@Override
								public void run() {
									// Select the last row so it will scroll into view...
									mListView.setSelection(mListView.getCount() - 1);
								}
							});

							if (isFirstBegin) {
								if (mOnChangeListener != null) {
									mOnChangeListener.onChange(mAuction);
								}
							}
						}
					}
				} else if (MessageConstants.ACTION_MESSAGE_SEND_FAILURE.equals(intent.getAction())) {
					ChatMessage chatMessage = (ChatMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
					if (chatMessage != null) {
						int index = mMessages.indexOf(chatMessage);
						if (index > -1) {
							chatMessage = mMessages.get(index);
							chatMessage.setMessageState(ChatMessage.MESSAGE_STATE_FAILURE);
							mAdapter.notifyDataSetChanged();
						}
					}
				} else if (MessageConstants.ACTION_MESSAGE_INFO_CHANGE.equals(action)) {
					// 更新竞拍人信息
					Auction auction = (Auction) intent.getSerializableExtra(CommonConstants.AUCTION);
					if (action != null && StringUtil.getDefaultString(mAuction.getAuctionId()).equals(auction.getAuctionId())) {
						updateAuctionInfo();
					}
				}
			}
		}
	};

	public void setAuction(Auction auction) {
		boolean isPhaseChange = false;
		if (CommonConstants.STATE_FINISHED.equals(auction.getStateCode())) {
			// 结束的时候需要刷新下聊天页面,保证用户不能操作
			isPhaseChange = true;
		} else {
			AuctionPhase newAuctionPhase = auction.getCurrentAuctionPhase();
			if (newAuctionPhase == null) {
				newAuctionPhase = new AuctionPhase();
			}
			if (StringUtil.getDefaultString(mAuctionPhase.getPhaseId()).equals(newAuctionPhase.getPhaseId())) {
				isPhaseChange = true;
			}
		}

		this.mAuction = auction;
		if (CommonConstants.STATE_FINISHED.equals(auction.getStateCode()) || CommonConstants.STATE_BEGINNING.equals(auction.getStateCode())) {
			updateView();
		} else {
			updateTopView(false);
		}
		if (isPhaseChange) {
			mAdapter.notifyDataSetChanged();
			mListView.post(new Runnable() {
				@Override
				public void run() {
					// Select the last row so it will scroll into view...
					mListView.setSelection(mListView.getCount() - 1);
				}
			});
		}
	}

	@OnClick({R.id.iv_menu})
	void onBtnMenuClick(View v) {
		if (viewInput.getVisibility() == View.VISIBLE) {
			ivMenu.setImageResource(R.drawable.ebei_btn_keyboard);
			viewInput.setVisibility(View.GONE);
			viewOperate.setVisibility(View.VISIBLE);
		} else {
			ivMenu.setImageResource(R.drawable.ebei_btn_menu_for_editview);
			viewInput.setVisibility(View.VISIBLE);
			viewOperate.setVisibility(View.GONE);
		}
	}

	@OnClick({R.id.view_begin})
	void onBtnBeginClick(View v) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("auctionId", mAuction.getAuctionId());

		HttpService mHttpService = HttpService.getInstance();
		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.activeNextAuctionPhase(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
			}

			@Override
			public void onSuccess(String result) {
				ViewUtil.toastMsg(mContext, R.string.ebei_operate_success);
				mAuction.setStateCode(CommonConstants.STATE_BEGINNING);
				// 更新阶段信息
				List<AuctionPhase> auctionPhases = mAuction.getAuctionPhases();
				if (auctionPhases.size() > 0) {
					mAuctionPhase = auctionPhases.get(0);
					mAuctionPhase.setPhaseState("1");
					// 设置当前报价为起拍价
					mAuctionPhase.setPhaseResult(StringUtil.getDefaultString(mAuctionPhase.getStartPrice()));
					mAuctionPhase.setPhaseOurResult(StringUtil.getDefaultString(mAuctionPhase.getStartPrice()));
				}
				updateView();

				if (mOnChangeListener != null) {
					mOnChangeListener.onChange(mAuction);
				}
			}
		}, String.class);
	}

	@OnClick({R.id.btn_send})
	void onBtnSendClick(View v) {
		if (StringUtil.isEmpty(etMessage.getText().toString())) {
			return;
		}

		final ChatMessage chatMessage = new ChatMessage();
		chatMessage.getNewSendMessage();
		chatMessage.setAuctionId(mAuction.getAuctionId());
		chatMessage.setMessageType(ChatMessage.MESSAGE_TYPE_NORMAL);
		chatMessage.setMessageDetail(etMessage.getText().toString());
		mChatMessageDao.insert(chatMessage);
		startMessageSendService();

		// 界面直接先显示,后期再更新消息状态
		mMessages.add(chatMessage);
		mAdapter.notifyDataSetChanged();
		mListView.setSelection(mMessages.size() - 1);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("messageDetail", chatMessage.getMessageDetail());
		Map<String, String> auctionMap = new HashMap<String, String>();
		auctionMap.put("auctionId", mAuction.getAuctionId());
		params.put("auction", auctionMap);
		params.put("messageId", chatMessage.getMessageId());

		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.sendMessage(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
				chatMessage.setSendFail();
				mAdapter.notifyDataSetChanged();
			}

			@Override
			public void onSuccess(String result) {
				if (StringUtil.isEmpty(result)) {
					ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
					chatMessage.setSendFail();
					mAdapter.notifyDataSetChanged();
					return;
				}
			}
		}, String.class, false);

		etMessage.setText("");
	}

	@OnClick({R.id.btn_operate1, R.id.btn_operate2})
	void onBtnOperateClick(View v) {
		String operateName = ((Button) v).getText().toString();
		if (getString(R.string.ebei_bid_mine).equals(operateName) || getString(R.string.ebei_bid_others).equals(operateName)) {
			Intent intent = new Intent(mContext, AuctionBidActivity.class);
			intent.putExtra(CommonConstants.AUCTION, mAuction);
			intent.putExtra(CommonConstants.TITLE_NAME, operateName);
			startActivity(intent);
		} else if (getString(R.string.ebei_operate_price_add).equals(operateName) || getString(R.string.ebei_operate_price_giveup).equals(operateName)) {
			sendCommand(operateName);
		}
	}

	private void startMessageSendService() {
		Intent messageIntent = new Intent(mContext, MessageSendService.class);
		messageIntent.setAction("MessageSendService");
		mContext.startService(messageIntent);
	}

	private void sendCommand(String operateName) {
		final ChatMessage chatMessage = new ChatMessage();
		chatMessage.getNewSendMessage();
		chatMessage.setAuctionId(mAuction.getAuctionId());
		chatMessage.setMessageType(ChatMessage.MESSAGE_TYPE_COMMAND_SEND);
		chatMessage.setMessageDetail("【" + getString(R.string.ebei_command) + "】" + operateName);
		mChatMessageDao.insert(chatMessage);
		startMessageSendService();

		String commandType = "";
		if (getString(R.string.ebei_operate_price_add).equals(operateName)) {
			commandType = ChatMessage.COMMAND_TYPE_ADD;
		} else if (getString(R.string.ebei_operate_price_giveup).equals(operateName)) {
			commandType = ChatMessage.COMMAND_TYPE_GIVEUP;
		}

		// 界面直接先显示,后期再更新消息状态
		mMessages.add(chatMessage);
		mAdapter.notifyDataSetChanged();
		mListView.setSelection(mMessages.size() - 1);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("auctionId", mAuction.getAuctionId());
		params.put("commandType", commandType);
		params.put("messageId", chatMessage.getMessageId());

		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.sendCommand(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
				chatMessage.setSendFail();
				mAdapter.notifyDataSetChanged();
			}

			@Override
			public void onSuccess(String result) {
				if (StringUtil.isEmpty(result)) {
					ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
					chatMessage.setSendFail();
					mAdapter.notifyDataSetChanged();
					return;
				}
			}
		}, String.class, false);
	}

	private void confirmCommand(String commandId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", mUserId);
		params.put("commandId", commandId);

		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.confirmCommand(params);
		final CommonAlertDialogFragment mProgressDialog = ViewUtil.showProgressDialog(mContext, -1, R.string.ebei_loading);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				ViewUtil.dismissDialog(mProgressDialog);
				ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
			}

			@Override
			public void onSuccess(String result) {
				ViewUtil.dismissDialog(mProgressDialog);
				if (StringUtil.isEmpty(result)) {
					ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
					return;
				}
			}
		}, String.class, false);
	}

	private void recallCommand(String bidId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("bidId", bidId);

		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.recallCommand(params);
		final CommonAlertDialogFragment mProgressDialog = ViewUtil.showProgressDialog(mContext, -1, R.string.ebei_loading);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {

			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				ViewUtil.dismissDialog(mProgressDialog);
				ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
			}

			@Override
			public void onSuccess(String result) {
				ViewUtil.dismissDialog(mProgressDialog);
				if (StringUtil.isEmpty(result)) {
					ViewUtil.toastMsg(mContext, R.string.ebei_send_failure);
					return;
				}
			}
		}, String.class, false);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ebei_view_auction_live, null);
		unbinder = ButterKnife.bind(this, view);
		mContext = getActivity();
		Intent intent = getActivity().getIntent();
		if (intent != null) {
			mAuction = (Auction) intent.getSerializableExtra(CommonConstants.AUCTION);
			mCurrentTab = intent.getIntExtra("currentTab", 0);
		}

		initView();

		registerBroadCast();
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	private void initView() {

		mUserId = StringUtil.getDefaultString(SPManager.getInstance().get(SPConstants.USER_ID, ""));
		mHttpService = HttpService.getInstance();
		mChatMessageDao = ChatMessageDao.getInstance();

		mAdapter = new ChatAdapter(mContext, mMessages);
		mListView.setAdapter(mAdapter);

		mAuctionUser = mAuction.getCurrentAuctionUser();
		if (mAuctionUser == null) {
			mAuctionUser = new AuctionUser();
		}
		mAuctionPhase = mAuction.getCurrentAuctionPhase();
		if (mAuctionPhase == null) {
			mAuctionPhase = new AuctionPhase();
		}

		updateView();

		loadMessage();
	}

	private void updateView() {
		if (CommonConstants.STATE_PUBLISHED.equals(mAuction.getStateCode())) {
			viewNotBegin.setVisibility(View.VISIBLE);
			viewAuctionInfo.setVisibility(View.GONE);

			// 必须是[今日竞拍],且登陆人是直播员才能开始
			if (mCurrentTab == HomepageActivity.TAB_TODAY && CommonConstants.AUCTION_USER_BROADCASTER.equals(mAuctionUser.getType())) {
				mBeginView.setVisibility(View.VISIBLE);
			} else {
				mBeginView.setVisibility(View.GONE);
			}
		} else {
			viewNotBegin.setVisibility(View.GONE);
			mBeginView.setVisibility(View.GONE);
			viewAuctionInfo.setVisibility(View.VISIBLE);

			if (CommonConstants.STATE_BEGINNING.equals(mAuction.getStateCode())) {
				viewBottom.setVisibility(View.VISIBLE);
			} else {
				viewBottom.setVisibility(View.GONE);
			}
		}

		updateTopView(true);

		if (CommonConstants.AUCTION_USER_CHAIRMAN.equals(mAuctionUser.getType())
				|| CommonConstants.AUCTION_USER_PRESIDENT.equals(mAuctionUser.getType())
				|| CommonConstants.AUCTION_USER_AUDIENCE.equals(mAuctionUser.getType())
				|| CommonConstants.AUCTION_USER_REVIEW_HEADMAN.equals(mAuctionUser.getType())
				|| CommonConstants.AUCTION_USER_REVIEW_BUTTMAN.equals(mAuctionUser.getType())) {
			ivMenu.setVisibility(View.GONE);
			viewInput.setVisibility(View.VISIBLE);
			viewOperate.setVisibility(View.GONE);
		} else {
			ivMenu.setVisibility(View.VISIBLE);
			if (CommonConstants.AUCTION_USER_BROADCASTER.equals(mAuctionUser.getType())) {
				btnOperate1.setText(R.string.ebei_bid_mine);
				btnOperate2.setText(R.string.ebei_bid_others);
				btnOperate1.setTextColor(getResources().getColor(R.color.ebei_orange));
			} else if (CommonConstants.AUCTION_USER_AUTHORIZER.equals(mAuctionUser.getType())
					|| CommonConstants.AUCTION_USER_AREA_AUTHORIZER.equals(mAuctionUser.getType())) {
				btnOperate1.setText(R.string.ebei_operate_price_add);
				btnOperate2.setText(R.string.ebei_operate_price_giveup);
				btnOperate2.setTextColor(getResources().getColor(R.color.ebei_red));
			}
		}
	}

	private void updateTopView(boolean isFirst) {
		mAuctionPhase = mAuction.getCurrentAuctionPhase();
		if (mAuctionPhase == null) {
			mAuctionPhase = new AuctionPhase();
		}

		final List<AuctionPhase> auctionPhases = mAuction.getAuctionPhases();
		AuctionPhase auctionPhase = mAuctionPhase;
		String currentPhaseId = mAuctionPhase == null ? "" : mAuctionPhase.getPhaseId();
		if (CommonConstants.STATE_FINISHED.equals(mAuction.getStateCode()) && auctionPhases.size() > 0) {
			auctionPhase = auctionPhases.get(auctionPhases.size() - 1);
			currentPhaseId = auctionPhase.getPhaseId();
		}
		String content = StringUtil.getDefaultString(auctionPhase.getPhaseName(), "-");
		mTvPhaseName.setText(content);

		AuctionAdapter mAuctionAdapter = new AuctionAdapter(mContext, mCurrentTab, null);
		String result = auctionPhase.getPhaseResult();
		result = StringUtil.getDefaultString(result, auctionPhase.getStartPrice());
		if (!StringUtil.isEmpty(result)) {
			result += StringUtil.getDefaultString(auctionPhase.getUnit());
			result += auctionPhase.getPhaseResultRateString(auctionPhase.getPhaseResultRate());
		}
		result = StringUtil.getDefaultString(result, "-");
		content = StringUtil.getDefaultString(result);
		mTvCurrentPrice.setText(content);

		mAuctionAdapter.setColumnColor(mTvCurrentPrice, auctionPhase, currentPhaseId, false);
		int color = mTvCurrentPrice.getCurrentTextColor();
		if (color != getResources().getColor(R.color.ebei_red)) {
			color = getResources().getColor(R.color.ebei_text_common_dark);
		}
		mTvCurrentPrice.setTextColor(color);
		content = (auctionPhase.getResultBidder() == null ? "" : (
				StringUtil.getDefaultString(auctionPhase.getResultBidder().getBidderAuctionCode()) + StringUtil.getDefaultString(auctionPhase.getResultBidder().getBidderName())));
		content = StringUtil.getDefaultString(content, "-");
		mTvCompany.setText(content);
		mTvCompany.setTextColor(color);
	}

	private void updateTopViewOld(boolean isFirst) {
		mAuctionPhase = mAuction.getCurrentAuctionPhase();
		if (mAuctionPhase == null) {
			mAuctionPhase = new AuctionPhase();
		}

		if (mCurrentTab != HomepageActivity.TAB_BEGIN) {
			String currentPhaseId = mAuctionPhase == null ? "" : mAuctionPhase.getPhaseId();
			AuctionAdapter mAuctionAdapter = new AuctionAdapter(mContext, mCurrentTab, null);
			List<Integer> widths = new ArrayList<Integer>();
			final List<AuctionPhase> auctionPhases = mAuction.getAuctionPhases();
			viewPhase.removeAllViews();

			for (AuctionPhase auctionPhase : auctionPhases) {
				LinearLayout view = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_auction_info_item, null);
				TextView tabText = (TextView) view.findViewById(R.id.tv_tab_name);
				TextView otherText = (TextView) view.findViewById(R.id.tv_other);
				TextView mineText = (TextView) view.findViewById(R.id.tv_mine);

				tabText.setText(StringUtil.getDefaultString(auctionPhase.getPhaseName(), "-"));
				mAuctionAdapter.setColumnNameColor(tabText, auctionPhase, currentPhaseId);
				otherText.setText(mAuctionAdapter.getPhaseContent(auctionPhase));
				mAuctionAdapter.setColumnColor(otherText, auctionPhase, currentPhaseId, false);
				mineText.setText(mAuctionAdapter.getPhaseOurContent(auctionPhase));
				mAuctionAdapter.setColumnColor(mineText, auctionPhase, currentPhaseId, true);
				viewPhase.addView(view);

				view.measure(0, 0);
				widths.add(view.getMeasuredWidth());
			}
			if (!isFirst) {
				// 定位到当期阶段
				if (auctionPhases.size() > 0) {
					int currentPhaseIndex = 0;
					if (CommonConstants.STATE_FINISHED.equals(mAuction.getStateCode())) {
						currentPhaseIndex = auctionPhases.size() - 1;
					} else {
						if (mAuctionPhase != null) {
							currentPhaseIndex = auctionPhases.indexOf(mAuctionPhase);
						}
					}

					int parentWidth = ViewUtil.getScreenSize(getActivity()).widthPixels - ViewUtil.dp2px(mContext, 40) -
							ViewUtil.getTextSize(getResources().getDimensionPixelSize(R.dimen.ebei_common_small_text_size), getString(R.string.ebei_highest)).widthPixels;
					if (currentPhaseIndex > 0) {
						int diff = 0;
						for (int i = 0; i <= currentPhaseIndex; i++) {
							diff += widths.get(i);
						}
						scrollDiff = diff - parentWidth;
						if (scrollDiff > 0) {
							new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
								@Override
								public void run() {
									scrollviewPhase.scrollTo(scrollDiff, 100);
								}
							}, 0);
						}
					}
				}
			}
			else {
				if (listener == null) {
					listener = new ViewTreeObserver.OnGlobalLayoutListener() {
						@Override
						public void onGlobalLayout() {
							List<Integer> widths = new ArrayList<Integer>();
							for (int i = 0; i < viewPhase.getChildCount(); i++) {
								View view = viewPhase.getChildAt(i);
								widths.add(view.getMeasuredWidth());
							}
							// 定位到当期阶段
							if (auctionPhases.size() > 0) {
								int currentPhaseIndex = 0;
								if (CommonConstants.STATE_FINISHED.equals(mAuction.getStateCode())) {
									currentPhaseIndex = auctionPhases.size() - 1;
								} else {
									if (mAuctionPhase != null) {
										currentPhaseIndex = auctionPhases.indexOf(mAuctionPhase);
									}
								}

								int parentWidth = ViewUtil.getScreenSize(getActivity()).widthPixels - ViewUtil.dp2px(mContext, 40) -
										ViewUtil.getTextSize(getResources().getDimensionPixelSize(R.dimen.ebei_common_small_text_size), getString(R.string.ebei_highest)).widthPixels;
								if (currentPhaseIndex > 0) {
									int diff = 0;
									for (int i = 0; i <= currentPhaseIndex; i++) {
										diff += widths.get(i);
									}
									scrollDiff = diff - parentWidth;
									if (scrollDiff > 0) {
										new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
											@Override
											public void run() {
												scrollviewPhase.scrollTo(scrollDiff, 0);
											}
										}, 0);
									}
								}
							}
						}
					};
					vtObserver = scrollviewPhase.getViewTreeObserver();
					vtObserver.addOnGlobalLayoutListener(listener);
				}
			}
//			vtObserver.removeOnGlobalLayoutListener(listener);

		}
	}

	private void updateAuctionInfo() {
		// 先调用接口拉下最新的数据
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("auctionId", mAuction.getAuctionId());

		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.getMessageByWeb(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
			}

			@Override
			public void onSuccess(final String result) {
				new AsyncTask<Void, Void, Void>() {

					private Auction auction;

					@Override
					protected Void doInBackground(Void... params) {
						if (!StringUtil.isEmpty(result)) {
							try {
								auction = new Gson().fromJson(result, Auction.class);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void aVoid) {
						super.onPostExecute(aVoid);
						if (auction != null) {
							mAuction = auction;
							updateView();
							if (mOnChangeListener != null) {
								mOnChangeListener.onChange(mAuction);
							}
						}
					}
				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
		}, String.class, false);
	}

	private void loadMessage() {
		// 先调用接口拉下最新的数据
		mProgressDialog = ViewUtil.showProgressDialog(mContext, -1, R.string.ebei_loading);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("auctionId", mAuction.getAuctionId());

		HttpAuctionServiceRx mHttpAuctionServiceRx = mHttpService.getRxGsonRetrofit().create(HttpAuctionServiceRx.class);
		final Call<ResponseBody> call = mHttpAuctionServiceRx.getMessageByWeb(params);
		mHttpService.executeHttp(mContext, call, new HttpService.HttpListener<String>() {
			@Override
			public void onStart() {
				mLoadMessageJson = "";
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				loadMessageFromLocal();
			}

			@Override
			public void onSuccess(String result) {
				mLoadMessageJson = result;
				loadMessageFromLocal();
			}
		}, String.class, false);
	}

	private void loadMessageFromLocal() {
		if (mProgressDialog == null || !mProgressDialog.isShowing()) {
			mProgressDialog = ViewUtil.showProgressDialog(mContext, -1, R.string.ebei_loading);
		}
		new AsyncTask<Void, Void, Void>() {

			List<ChatMessage> messages;

			@Override
			protected Void doInBackground(Void... params) {
				if (!StringUtil.isEmpty(mLoadMessageJson)) {
					try {
						JSONObject jsonObject = new JSONObject(mLoadMessageJson);
						JSONArray messageArray = jsonObject.optJSONArray("messages");
						if (messageArray != null) {
							List<ChatMessage> messages = new ArrayList<ChatMessage>();
							for (int i = 0; i < messageArray.length(); i++) {
								JSONObject messageObject = messageArray.getJSONObject(i);
								ChatMessage chatMessage = new ChatMessage();
								chatMessage.setMessageId(messageObject.optString("messageId"));
								// 查看本地有没有
								ChatMessage chatMessageL = mChatMessageDao.getChatMessageById(chatMessage.getMessageId());
								if (chatMessageL != null) {
									chatMessage = chatMessageL;
								}

								chatMessage.setAuctionId(mAuction.getAuctionId());
								chatMessage.setMessageDetail(messageObject.optString("messageDetail"));
								chatMessage.setFromUserId(messageObject.optString("userId"));
								chatMessage.setFromUserName(messageObject.optString("userName"));
								chatMessage.setSendTime(messageObject.optString("time"));
								chatMessage.setTitleText(messageObject.optString("titleText"));
								String nowPhaseResultNames = StringUtil.getDefaultString(messageObject.optString("nowPahseResultName"));
								if (nowPhaseResultNames.length() > 0) {
									nowPhaseResultNames = nowPhaseResultNames.replace("[", "").replace("]", "").replace("\"", "");
								}
								chatMessage.setNowPhaseResultNames(nowPhaseResultNames);
								String messageType = "";
								int messageTypeCode = messageObject.optInt("messageTypeCode");
								if (messageTypeCode == 1 || messageTypeCode == 2) {
									messageType = ChatMessage.MESSAGE_TYPE_COMMAND_SEND;
								} else if (messageTypeCode == 3) {
									messageType = ChatMessage.MESSAGE_TYPE_COMMAND_COMFIRM;
								} else if (messageTypeCode == 4) {
									messageType = ChatMessage.MESSAGE_TYPE_OUR_PRICE;
								} else if (messageTypeCode == 5) {
									messageType = ChatMessage.MESSAGE_TYPE_THEIR_PRICE;
								} else if (messageTypeCode == 6) {
									messageType = ChatMessage.MESSAGE_TYPE_PHASE_SWITCH;
								} else if (messageTypeCode == 7) {
									messageType = ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL;
								} else if (messageTypeCode == 0) {
									messageType = ChatMessage.MESSAGE_TYPE_NORMAL;
								} else {
									// 8直播间信息修改
									continue;
								}
								chatMessage.setMessageType(messageType);

								JSONObject commandObject = messageObject.optJSONObject("command");
								if (commandObject != null) {
									chatMessage.setCommandId(commandObject.optString("commandId"));
									chatMessage.setCommandType(commandObject.optString("commandTypeCode"));
								}

								JSONObject commandConfirmObject = messageObject.optJSONObject("commandConfirm");
								if (commandConfirmObject != null) {
									chatMessage.setCommandId(commandConfirmObject.optString("confrimCommadnId"));
								}

								JSONObject bidObject = messageObject.optJSONObject("bid");
								if (bidObject != null) {
									chatMessage.setBidId(bidObject.optString("bidId"));
									chatMessage.setPhaseId(bidObject.optString("phaseId"));
									JSONObject recallBidObject = bidObject.optJSONObject("recallBid");
									if (recallBidObject != null) {
										chatMessage.setRecalledBidId(recallBidObject.optString("bidId"));
									}
								}

								messages.add(chatMessage);
							}
							if (messages.size() > 0) {
								mChatMessageDao.insertOrUpdateList(messages);
							}
						}
					} catch (Exception e) {}
				}

				messages = ChatMessageDao.getInstance().getChatMessageList(mAuction.getAuctionId());
				if (messages != null) {
					Collections.sort(messages, new Comparator<ChatMessage>() {
						@Override
						public int compare(ChatMessage lhs, ChatMessage rhs) {
							return StringUtil.getDefaultString(lhs.getSendTime()).compareTo(rhs.getSendTime());
						}
					});

					for (int i = mMessages.size() - 1; i > -1; i--) {
						ChatMessage chatMessage = mMessages.get(i);
						if (ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL.equals(chatMessage.getMessageType())
								|| ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
								|| ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(chatMessage.getMessageType())) {

							if (ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL.equals(chatMessage.getMessageType())) {
								// 如果消息是撤回,就不管最高价,直接用撤回消息里返回的价格
								mAuctionPhase.setPhaseResult(chatMessage.getPrice());
							} else if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
									|| ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(chatMessage.getMessageType())) {
								// 如果消息是出价的消息,要更新现有的报价
								if (mAuctionPhase.compare(chatMessage.getPrice(), mAuctionPhase.getPhaseResult()) > 0) {
									mAuctionPhase.setPhaseResult(chatMessage.getPrice());
								}
							}
							return null;
						}
					}

				}
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				super.onPostExecute(aVoid);
				ViewUtil.dismissDialog(mProgressDialog);
				Activity activity = getActivity();
				if (activity != null && !activity.isFinishing()) {
					mMessages.clear();
					if (messages != null) {
						mMessages.addAll(messages);
					}
					mAdapter.notifyDataSetChanged();
					if (mMessages.size() > 0) {
						mListView.setSelection(mMessages.size() - 1);
					}
				}
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_SEND_FAILURE);
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_INFO_CHANGE);
		mContext.registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
		mContext.unregisterReceiver(mBroadcastReceiver);
		/*if (vtObserver!=null&&listener!=null&&vtObserver.isAlive()) {
			vtObserver.removeOnGlobalLayoutListener(listener);
		}*/
	}

	class ChatAdapter extends BaseAdapter {

		private Context mContext;
		private List<ChatMessage> mMessages;

		public ChatAdapter(Context context, List<ChatMessage> messages) {
			mContext = context;
			mMessages = messages;
		}

		@Override
		public int getCount() {
			return mMessages.size();
		}

		@Override
		public Object getItem(int position) {
			return mMessages.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder mViewHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_chat_item, null);
				mViewHolder = new ViewHolder();
				mViewHolder.set(convertView);
				convertView.setTag(mViewHolder);
			} else {
				mViewHolder = (ViewHolder) convertView.getTag();
			}
			mViewHolder.setPosition(position);

			ChatMessage message = mMessages.get(position);
			TextView tvName, tvTime, tvMsg;
			mViewHolder.btnMsgOperateLeft.setVisibility(View.GONE);
			mViewHolder.btnMsgOperateRight.setVisibility(View.GONE);
			if (mUserId.equals(message.getFromUserId())) {
				mViewHolder.viewLeft.setVisibility(View.GONE);
				mViewHolder.viewRight.setVisibility(View.VISIBLE);
				tvName = mViewHolder.tvNameRight;
				tvTime = mViewHolder.tvTimeRight;
				tvMsg = mViewHolder.tvMsgRight;
				ChatMessage lastPriceMessage = getLastPriceMessage();
				if ((ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(message.getMessageType())
						|| ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(message.getMessageType()))
						&& lastPriceMessage != null && lastPriceMessage.getMessageId().equals(message.getMessageId())) {
					if (!getIsCommandRecall(message)) {
						if (CommonConstants.STATE_BEGINNING.equals(mAuction.getStateCode())
								&& StringUtil.getDefaultString(mAuctionPhase.getPhaseId()).equals(message.getPhaseId())) {
							// 如果是[本方报价]或者[竞方报价]的最新的记录,可以撤回
							mViewHolder.btnMsgOperateRight.setVisibility(View.VISIBLE);
							mViewHolder.btnMsgOperateRight.setText(R.string.ebei_recall);
							mViewHolder.btnMsgOperateRight.setTextColor(getResources().getColor(R.color.ebei_blue));
							mViewHolder.btnMsgOperateRight.setOnClickListener(mViewHolder);
						}
					} else {
						// 如果是撤回的消息,显示已撤回
						mViewHolder.btnMsgOperateRight.setVisibility(View.VISIBLE);
						mViewHolder.btnMsgOperateRight.setText(R.string.ebei_recall_already);
						mViewHolder.btnMsgOperateRight.setTextColor(getResources().getColor(R.color.ebei_text_common_light));
						mViewHolder.btnMsgOperateRight.setOnClickListener(null);
					}
				} else if (CommonConstants.AUCTION_USER_AUTHORIZER.equals(mAuctionUser.getType())) {
					// 如果是授权人员,当发出的指令有一个广播员[确认收到],指令就标记为[已收到]
					boolean isCommandConfirm = getIsCommandConfirm(message, false);
					if (ChatMessage.MESSAGE_TYPE_COMMAND_SEND.equals(message.getMessageType()) && isCommandConfirm) {
						mViewHolder.btnMsgOperateRight.setVisibility(View.VISIBLE);
						mViewHolder.btnMsgOperateRight.setText(R.string.ebei_confirmed);
						mViewHolder.btnMsgOperateRight.setTextColor(getResources().getColor(R.color.ebei_text_common_light));
						mViewHolder.btnMsgOperateRight.setOnClickListener(null);
					}
				}

				if (ChatMessage.MESSAGE_STATE_SENDING.equals(message.getMessageState())) {
					mViewHolder.viewLoading.setVisibility(View.VISIBLE);
					mViewHolder.ivState.setVisibility(View.GONE);
				} else if (ChatMessage.MESSAGE_STATE_FAILURE.equals(message.getMessageState())) {
					mViewHolder.viewLoading.setVisibility(View.GONE);
					mViewHolder.ivState.setVisibility(View.VISIBLE);
				} else {
					mViewHolder.viewLoading.setVisibility(View.GONE);
					mViewHolder.ivState.setVisibility(View.GONE);
				}
			} else {
				mViewHolder.viewLeft.setVisibility(View.VISIBLE);
				mViewHolder.viewRight.setVisibility(View.GONE);
				tvName = mViewHolder.tvNameLeft;
				tvTime = mViewHolder.tvTimeLeft;
				tvMsg = mViewHolder.tvMsgLeft;

				// 指令后面后有[确认收到]的按钮,确认后指令标记为[已收到]
				if (CommonConstants.AUCTION_USER_BROADCASTER.equals(mAuctionUser.getType())) {
					boolean isCommandConfirm = getIsCommandConfirm(message, true);
					if (ChatMessage.MESSAGE_TYPE_COMMAND_SEND.equals(message.getMessageType())) {
						if (isCommandConfirm) {
							mViewHolder.btnMsgOperateLeft.setVisibility(View.VISIBLE);
							mViewHolder.btnMsgOperateLeft.setText(R.string.ebei_confirmed);
							mViewHolder.btnMsgOperateLeft.setTextColor(getResources().getColor(R.color.ebei_text_common_light));
							mViewHolder.btnMsgOperateLeft.setOnClickListener(null);
						} else {
							if (CommonConstants.STATE_BEGINNING.equals(mAuction.getStateCode())) {
								mViewHolder.btnMsgOperateLeft.setVisibility(View.VISIBLE);
								mViewHolder.btnMsgOperateLeft.setText(R.string.ebei_receipt_confirm);
								mViewHolder.btnMsgOperateLeft.setTextColor(getResources().getColor(R.color.ebei_blue));
								mViewHolder.btnMsgOperateLeft.setOnClickListener(mViewHolder);
							}
						}
					}
				}
			}

			tvName.setText(message.getFromUserName());
			if (mUserId.equals(message.getFromUserId())) {
				tvName.setText(R.string.ebei_me);
			}
			tvTime.setText(TimeUtil.getDisplayTime(TimeUtil.getDateToString(new Date(Long.valueOf(message.getSendTime())))));

			tvMsg.setText(message.getMessageDetail());
			tvMsg.setTextColor(getResources().getColor(R.color.ebei_text_common_dark));
			if (ChatMessage.COMMAND_TYPE_ADD.equals(message.getCommandType())) {
				tvMsg.setTextColor(getResources().getColor(R.color.ebei_blue));
			} else if (ChatMessage.COMMAND_TYPE_GIVEUP.equals(message.getCommandType())) {
				tvMsg.setTextColor(getResources().getColor(R.color.ebei_red));
			}
			// 如果是对方的竞价消息,前面的文字用颜色区分开
			SpannableStringBuilder builder = new SpannableStringBuilder(tvMsg.getText().toString());
			if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(message.getMessageType())) {
				tvMsg.setText("【" + getString(R.string.ebei_bid_mine) + "】" + tvMsg.getText().toString());
				builder = new SpannableStringBuilder(tvMsg.getText().toString());
				ForegroundColorSpan blueSpan = new ForegroundColorSpan(getResources().getColor(R.color.ebei_orange));
				builder.setSpan(blueSpan, 0, 6, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			} else if (ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(message.getMessageType())) {
				tvMsg.setText("【" + getString(R.string.ebei_bid_others) + "】" + tvMsg.getText().toString());
				builder = new SpannableStringBuilder(tvMsg.getText().toString());
				ForegroundColorSpan orangeSpan = new ForegroundColorSpan(getResources().getColor(R.color.ebei_blue));
				builder.setSpan(orangeSpan, 0, 6, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			} else if (!StringUtil.isEmpty(message.getTitleText())) {
				tvMsg.setText(message.getTitleText() + tvMsg.getText().toString());
				int index = message.getTitleText().length();
				builder = new SpannableStringBuilder(tvMsg.getText().toString());
				ForegroundColorSpan orangeSpan = new ForegroundColorSpan(getResources().getColor(R.color.ebei_red));
				builder.setSpan(orangeSpan, 0, index, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			}
			// 解析文字中是否有碧桂园,有的话红色标识
			List<Integer> flagRedIndexs = new ArrayList<Integer>();
			List<Integer> flagRedEndIndexs = new ArrayList<Integer>();
			String content = tvMsg.getText().toString();
			AuctionBidder auctionBidder = mAuction.getOurAuctionBidder();
			while (content.contains("碧桂园")) {
				int index = content.indexOf("碧桂园");
				if (index > -1) {
					flagRedEndIndexs.add(index + 3);

					if (!StringUtil.isEmpty(auctionBidder.getBidderAuctionCode())) {
						String str = content.substring(0, index).trim();
						if (str.endsWith(auctionBidder.getBidderAuctionCode())) {
							index = str.length() - auctionBidder.getBidderAuctionCode().length();
						}
					}
					flagRedIndexs.add(index);
				}
				content = content.replaceFirst("碧桂园", "碧碧碧");
			}
			if (flagRedIndexs.size() > 0) {
				for (int i = 0; i < flagRedIndexs.size(); i++) {
					int index = flagRedIndexs.get(i);
					int endIndex = flagRedEndIndexs.get(i);
					ForegroundColorSpan flagSpan = new ForegroundColorSpan(getResources().getColor(R.color.ebei_red));
					builder.setSpan(flagSpan, index, endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				}
			}
			// 解析当前报价里的阶段数据,有的话红色标识
			String nowPhaseResultNames = message.getNowPhaseResultNames();
			if (!StringUtil.isEmpty(nowPhaseResultNames)) {
				String[] nowPhaseResultNameArray = nowPhaseResultNames.split(",");
				int indexFirst = content.lastIndexOf("】");
				for (String nowPhaseResultName : nowPhaseResultNameArray) {
					nowPhaseResultName = nowPhaseResultName.trim();
					ForegroundColorSpan flagSpan = new ForegroundColorSpan(getResources().getColor(R.color.ebei_red));
					int index = content.lastIndexOf(nowPhaseResultName);
					if (index > -1 && index > indexFirst) {
						int endIndex = content.indexOf("\n", index);
						if (endIndex > -1) {
							builder.setSpan(flagSpan, index, endIndex + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
						}
					}
				}
			}
			tvMsg.setText(builder);
			return convertView;
		}

		private ChatMessage getLastPriceMessage() {
			for (int i = mMessages.size() - 1; i > -1; i--) {
				ChatMessage chatMessage = mMessages.get(i);
				if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
						|| ChatMessage.MESSAGE_TYPE_THEIR_PRICE.equals(chatMessage.getMessageType())) {
					return chatMessage;
				}
			}
			return null;
		}

		private boolean getIsCommandConfirm(ChatMessage message, boolean isMine) {
			for (int i = mMessages.size() - 1; i > -1; i--) {
				ChatMessage chatMessage = mMessages.get(i);
				// 无论是谁确认,只要确认过就行
				if (ChatMessage.MESSAGE_TYPE_COMMAND_COMFIRM.equals(chatMessage.getMessageType())
						&& StringUtil.getDefaultString(message.getCommandId()).equals(chatMessage.getCommandId())) {
					if (!isMine || (isMine && mUserId.equals(chatMessage.getFromUserId()))) {
						return true;
					}
				}
				// 如果已经搜索到发出指令的位置,就没有必要再搜索了
				if (ChatMessage.MESSAGE_TYPE_COMMAND_SEND.equals(chatMessage.getMessageType())
						&& StringUtil.getDefaultString(chatMessage.getCommandId()).equals(message.getCommandId())) {
					return false;
				}
			}
			return false;
		}

		private boolean getIsCommandRecall(ChatMessage message) {
			for (int i = mMessages.size() - 1; i > -1; i--) {
				ChatMessage chatMessage = mMessages.get(i);
				if (ChatMessage.MESSAGE_TYPE_OUR_PRICE_RECALL.equals(chatMessage.getMessageType())
						&& mUserId.equals(chatMessage.getFromUserId())
						&& StringUtil.getDefaultString(message.getBidId()).equals(chatMessage.getRecalledBidId())) {
					return true;
				}
				// 如果已经搜索到发出竞价消息的位置,就没有必要再搜索了
				if (ChatMessage.MESSAGE_TYPE_OUR_PRICE.equals(chatMessage.getMessageType())
						&& StringUtil.getDefaultString(message.getBidId()).equals(chatMessage.getBidId())) {
					return false;
				}
			}
			return false;
		}

		class ViewHolder implements View.OnClickListener {
			@BindView(R.id.tv_name_left)
			TextView tvNameLeft;
			@BindView(R.id.tv_time_left)
			TextView tvTimeLeft;
			@BindView(R.id.tv_msg_left)
			TextView tvMsgLeft;
			@BindView(R.id.btn_msg_operate_left)
			Button btnMsgOperateLeft;
			@BindView(R.id.view_left)
			LinearLayout viewLeft;
			@BindView(R.id.tv_name_right)
			TextView tvNameRight;
			@BindView(R.id.tv_time_right)
			TextView tvTimeRight;
			@BindView(R.id.tv_msg_right)
			TextView tvMsgRight;
			@BindView(R.id.btn_msg_operate_right)
			Button btnMsgOperateRight;
			@BindView(R.id.view_right)
			LinearLayout viewRight;
			@BindView(R.id.view_loading)
			ProgressBar viewLoading;
			@BindView(R.id.iv_state)
			ImageView ivState;

			private int position;

			public void setPosition(int position) {
				this.position = position;
			}

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
					case R.id.btn_msg_operate_left:
						onOperateLeftClick(v);
						break;
					case R.id.btn_msg_operate_right:
						onOperateRightClick(v);
						break;
				}
			}

			void onOperateLeftClick(View v) {
				ChatMessage chatMessage = mMessages.get(position);
				confirmCommand(chatMessage.getCommandId());
			}

			void onOperateRightClick(View v) {
				ChatMessage chatMessage = mMessages.get(position);
				recallCommand(chatMessage.getBidId());
			}

			public void set (View view) {
				ButterKnife.bind(this, view);
			}
		}
	}

	public void setOnChangeListener(OnChangeListener l) {
		mOnChangeListener = l;
	}

	//定义接口
	public interface OnChangeListener {
		public void onChange(Auction auction);
	}

}
